# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# This is a sample controller
# this file is released under public domain and you can use without limitations
# -------------------------------------------------------------------------

# ---- example index page ----
from gluon.tools import Crud
crud = Crud(db)
import random
from gluon import current
import gluon.contrib.simplejson as sjson
import os
import json
from datetime import datetime
import time

# 自建模块modules
from levels import levels_map,svg_map

# 工具类复用代码：
def get_level_data(exp):
    "获取等级标志及信息"
    if not exp:
        exp = 1
    for i in range(len(levels_map)):
        #if exp**3 <= levels_map[i][0]:
        if exp <= levels_map[i][0]:
            level_data = levels_map[i-1]
            svg3 = svg_map.get(level_data[2][-3:])
            svg1 = svg_map.get(level_data[2][-1:])
            svg2 = svg_map.get(level_data[2][-2:])
            level_svg = svg3 if svg3 else (svg1 if svg1 else (svg2 if svg2 else ""))
            level = {
                "level_data":level_data,
                "level_svg":level_svg,
                "exp":exp,
            }
            return level
def get_resource(category,limit_page=None):
    if len(request.args):
        page=int(request.args[0])
    else:
        page=0
    items_per_page=5 if not limit_page else limit_page
    limitby=(page*items_per_page,(page+1)*items_per_page+1)
    #rows=db().select(db.prime.ALL,limitby=limitby)
    rows = db(
        db.resource.category==category
    ).select(db.resource.ALL, orderby=~db.resource.id, limitby=limitby)
    return dict(rows=rows,page=page,items_per_page=items_per_page)

def get_ymd(ymd):
    "2022年10月9日->20221009"
    y = ymd.split('年')[0]
    m = ymd.split('年')[1].split('月')[0].zfill(2)
    d = ymd.split('年')[1].split('月')[1].split('日')[0].zfill(2)
    return y + m + d

def get_now_ymd():
    "获取今天的日期20221018"
    return datetime.now().strftime("%Y%m%d")

def get_yesterday_ymd():
    "获取昨天的日期20221017"
    import datetime
    today=datetime.date.today()
    oneday=datetime.timedelta(days=1)
    yesterday=today-oneday
    return yesterday.strftime('%Y%m%d')

# 测试函数(开发新功能可以在这里进行)：
@auth.requires_membership('user')
def test():
    "测试"
    return get_resource("音乐",limit_page=1)

# ajax 函数
@auth.requires_membership('user')
def get_level():
    "根据经验获取等级"
    # 先使用打卡天数！
    #stories = db(
    #    db.seven_steps.created_by==auth.user_id
    #).select(db.seven_steps.ALL)
    ##return sjson.dumps(levels_map)
    #exp = len(stories) if len(stories) else 1
    # 经验
    max = db.seven_steps.exp.max()
    exp = db().select(max).first()[max]

    for i in range(len(levels_map)):
        #if exp**3 <= levels_map[i][0]:
        if exp <= levels_map[i][0]:
            level_data = levels_map[i-1]
            svg3 = svg_map.get(level_data[2][-3:])
            svg1 = svg_map.get(level_data[2][-1:])
            svg2 = svg_map.get(level_data[2][-2:])
            level_svg = svg3 if svg3 else (svg1 if svg1 else (svg2 if svg2 else ""))
            level = {
                "level_data":level_data,
                "level_svg":level_svg,
                "exp":exp,
            }
            return sjson.dumps(level)

@auth.requires_membership('user')
def get_seven_days():
    "七部曲当月哪些天记了日记"
    ym = get_ymd(request.vars.ymd)[:-2]
    stories = db(
        (db.seven_steps.ymd.like(ym + "%"))
        &(db.seven_steps.created_by==auth.user_id)
    ).select(db.seven_steps.ALL)
    days = [s.ymd for s in stories]
    return sjson.dumps(days)

def add_exp(data):
    "七部曲-经验增长"
    """
    """
    exp = 0
    #* 早起早睡
    #** 早睡<=23加25exp,23<x<=23:30加15,23<x<=24，加5， 24点之后就不加了
    #** 早起<=7加25exp,7<x<=7:30加15exp,7:30<x<=8:00，加5，7点半之后就不加了
    early = data.get('early')
    if early:
        x = early.split("-")[0]
        y = early.split("-")[1]
        if '21:00' < x <= '23:00':
            exp += 25
        elif '23:00' < x <= '23:30':
            exp += 15
        elif '23:00' < x <= '23:59':
            exp += 5
        if '05:00' < y <= '07:00':
            exp += 25
        elif '07:00' < y <= '07:30':
            exp += 15
        elif '07:30' < y <= '07:59':
            exp += 5

    #** 下拉膀胱经每20个加1，
    #** 卷腹每10个加1，
    #** 俯卧撑每5个加1，
    #** 深蹲每10个加1，
    #** 平板支撑每1min加5，
    #** 慢跑每0.1km加1,
    #** 该项上限200，分项上限50，后面看情况调整哦
    exercise = data.get('exercise')
    if exercise:
        exercise_xlpgj = exercise.split(",")[0].split(":")[1]
        exercise_xlpgj = min(int(exercise_xlpgj if exercise_xlpgj else 0) // 20, 50)
        exercise_jf = exercise.split(",")[1].split(":")[1]
        exercise_jf = min(int(exercise_jf if exercise_jf else 0) // 10, 50)
        exercise_fwc = exercise.split(",")[2].split(":")[1]
        exercise_fwc = min(int(exercise_fwc if exercise_fwc else 0) // 5, 50)
        exercise_sd = exercise.split(",")[3].split(":")[1]
        exercise_sd = min(int(exercise_sd if exercise_sd else 0) // 10, 50)
        exercise_pb = exercise.split(",")[4].split(":")[1]
        exercise_pb = min(int(exercise_pb if exercise_pb else 0) // 1 * 5, 50)
        exercise_mp = exercise.split(",")[5].split(":")[1]
        exercise_mp = min(int(float(exercise_mp if exercise_mp else 0) * 10), 50)
        exercise_kz = exercise.split(",")[6].split(":")[1]
        exercise_kz = min(int(float(exercise_kz if exercise_kz else 0) * 5), 50)
        exercise_tg = exercise.split(",")[7].split(":")[1]
        exercise_tg = min(int(float(exercise_tg if exercise_tg else 0) // 10), 50)
        exp += min(exercise_xlpgj + exercise_jf + exercise_fwc + exercise_sd + exercise_pb + exercise_mp + exercise_kz + exercise_tg, 200)

    #* 读书
    #5exp
    read = data.get('read')
    if read:
        exp += 5

    #* 持诵
    #5exp
    promise = data.get('promise')
    if promise:
        exp += 5

    #* 奋斗
    #5exp
    fight = data.get('fight')
    if fight:
        exp += 5

    #* 行善
    #10exp
    good = data.get('good')
    if good:
        exp += 5

    #* 反省
    #** 所得1
    reflection_get = data.get('reflection_get')
    if reflection_get:
        exp += 1
    #** 不足1
    reflection_lack = data.get('reflection_lack')
    if reflection_lack:
        exp += 1
    #** 感恩1
    reflection_thank = data.get('reflection_thank')
    if reflection_thank:
        exp += 1
    #** 计划1
    reflection_plan = data.get('reflection_plan')
    if reflection_plan:
        exp += 1
    #**全写了再加1
    if reflection_get and reflection_lack and reflection_thank and reflection_plan:
        exp += 1
    return exp

@auth.requires_membership('user')
def save_seven_story():
    "七部曲-保存"
    data = dict(request.vars)
    data['ymd'] = get_ymd(data['ymd'])
    try:
        # 2022年10月18日 增加经验值，只能增加当天的经验
        if get_now_ymd() == data['ymd']:
            s = db(
                (db.seven_steps.ymd==get_yesterday_ymd())
                &(db.seven_steps.created_by==auth.user_id)
            ).select(db.seven_steps.ALL).first()
            if s:
                l_exp = s.exp if s.exp  else 0
            else:
                l_exp = 0
            exp = add_exp(data)
            data['exp'] = exp + l_exp
            resp = sjson.dumps({"message":f"保存成功, 今日累计经验:{exp}!"})
        else:
            resp = sjson.dumps({"message":f"保存成功!"})
        db.seven_steps.update_or_insert(
            (db.seven_steps.ymd==data['ymd'])
            &(db.seven_steps.created_by==auth.user_id)
            ,**data)
        return resp
    except Exception as e:
        return sjson.dumps({"message":f"保存失败![{e}]"})

@auth.requires_membership('user')
def get_seven_story():
    "七部曲"
    # 哈哈涨姿势了，只要用sjson就可以实现ajax了
    # 测试
    #names=['Sunday','Monday','Tuesday','Wednesday',
    #'Thursday','Friday','Saturday']
    #return sjson.dumps(names)
    ymd = get_ymd(request.vars.ymd)
    s = db(
        (db.seven_steps.ymd==ymd)
        &(db.seven_steps.created_by==auth.user_id)
    ).select(db.seven_steps.ALL).first()
    story = {
     'early':s.early,
     'exercise':s.exercise,
     'read':s.read,
     'promise':s.promise,
     'fight':s.fight,
     'good':s.good,
     'reflection_get':s.reflection_get,
     'reflection_lack':s.reflection_lack,
     'reflection_thank':s.reflection_thank,
     'reflection_plan':s.reflection_plan,
     'ymd':ymd,
    } if s else {}
    return sjson.dumps(story)

# 视图函数：
def seven_rank():
    "七部曲排行"
    # 测试...
    #resp = [
    #]
    #for i in range(10):
    #    resp.append({
    #        'rank':i,
    #        'name':'kk' + str(i),
    #        'level': i ,
    #    })
    sql = """
        select first_name name, exp
        from
        (
           select b.id, b.first_name, b.last_name, max(a.exp) exp from seven_steps a
           left join auth_user b on a.created_by = b.id
           group by b.id,b.first_name,b.last_name
        )
       order by exp desc
    """
    rows = [{'name':r[0], 'exp':r[1] if r[1] else 0} for r in db.executesql(sql)]
    # 2022年10月29日搞几个NPC >>>
    # 与时俱进，这样可以激励自己！
    fake_data = [
        {'name':'院长放我出院','exp':21},
        {'name':'是你的胖虎吗','exp':30},
        {'name':'坠月河','exp':410},
        {'name':'无心人','exp':446},
        {'name':'你是真的狗','exp':100},
        {'name':'略略略','exp':6},
        {'name':'妖怪被师傅抓走了','exp':210},
        {'name':'送舟行','exp':138},
        {'name':'抠脚大仙','exp':237},
        {'name':'校长跳楼喊加油','exp':5},
        {'name':'唐氏表演法则 ','exp':323},
        {'name':'百善孝为先','exp':790},
        {'name':'昔年','exp':30},
        {'name':'多活一点给自己','exp':20},
        {'name':'看归处','exp':220},
        {'name':'猫籹','exp':320},
        {'name':'K','exp':120},
        {'name':'DontBeSilly','exp':1320},
        {'name':'崡峪','exp':620},
        {'name':'坚持下去便成王','exp':520},
        {'name':'恨别鸟惊心','exp':770},
        {'name':'鸢尾','exp':990},
        {'name':'村上','exp':10},
        {'name':'大哥','exp':20},
        {'name':'成都彭于晏','exp':1620},
        {'name':'莪掵甴莪卜甴兲','exp':1520},
        {'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
        #{'name':'唯有光','exp':60},
    ]
    for f in fake_data:
        f['exp'] += (time.time() - 1667044052.773504) // 86400 * 30
    rows.extend(fake_data)
    rows = sorted(rows, key = lambda rows:rows['exp'], reverse=True)
    #return sjson.dumps(rows)
    # 2022年10月29日搞几个NPC <<<
    for i in range(len(rows)):
        rows[i]['rank'] = i+1
        rows[i]['level'] = get_level_data(rows[i]['exp'])

    if len(request.args):
        page=int(request.args[0])
    else:
        page=0
    items_per_page=13
    max_page =  len(rows) // items_per_page
    max_rows = len(rows)
    limitby=(page*items_per_page,(page+1)*items_per_page + 1)
    rows = rows[limitby[0]:limitby[1]]
    return dict(rows=rows,page=page,items_per_page=items_per_page,max_page=max_page,max_rows=max_rows)

@auth.requires_membership('user')
def seven_step():
    "七部曲日课"
    return {}

def said():
    "他说"
    return get_resource("他说",limit_page=10)
def music():
    "音乐"
    return get_resource("音乐",limit_page=1)

def book():
    "读书"
    return get_resource("文字")

def collection():
    "收藏"
    if len(request.args):
        page=int(request.args[0])
    else:
        page=0
    items_per_page=5
    limitby=(page*items_per_page,(page+1)*items_per_page+1)
    #rows=db().select(db.prime.ALL,limitby=limitby)
    rows = db(
        db.resource.id==db.collection.resource,
        db.collection.created_by==db.auth_user.id
    ).select(db.resource.ALL, orderby=~db.resource.id, limitby=limitby)
    return dict(rows=rows,page=page,items_per_page=items_per_page)

def link():
    "网址"
    return get_resource("网址")

def website():
    "网站"
    return get_resource("网站")

def video():
    "视频"
    return get_resource("视频")

def index():
    "首页"
    return dict()

def about():
    "关于"
    return dict()


def see_what():
    "今天看什么"
    if not current.session.resource_id_queue:
        current.session.resource_id_queue = []

    if not request.args(0):
        resource_min = db().select(db.resource.ALL, orderby=db.resource.id).first()
        resource_max = db().select(db.resource.ALL, orderby=~db.resource.id).first()

        random_id = random.randint(resource_min.id,resource_max.id)
        resource = db(
            db.resource.id==random_id
        ).select().first()
        current.session.resource_id_queue = []
        current.session.resource_id_queue.append(resource.id)
        current.session.resource_id = resource.id
    elif request.args(0) == 'next':
        resource_min = db().select(db.resource.ALL, orderby=db.resource.id).first()
        resource_max = db().select(db.resource.ALL, orderby=~db.resource.id).first()

        random_id = random.randint(resource_min.id,resource_max.id)

        resource_l = db(
            db.resource.id>=random_id
        ).select().first()
        resource_s = db(
            db.resource.id<=random_id
        ).select().first()
        resource = resource_l if resource_l else resource_s

        current.session.resource_id_queue.append(resource.id)
        current.session.resource_id = resource.id
    elif request.args(0) == 'pre':
        if current.session.resource_id:
            del current.session.resource_id
            current.session.resource_id_queue.pop()
        pop_id = current.session.resource_id_queue.pop() if current.session.resource_id_queue else 0
        resource = db.resource(pop_id) or redirect(URL('index')) if pop_id else {}
#         resource = db(db.resource.id==session.resource_id_queue.pop()).select(orderby=~db.resource.title).first()
        if pop_id:
            current.session.resource_id_queue.append(resource.id)
            current.session.resource_id = resource.id
    else:
        resource = db(
            db.resource.id==request.args(0)
        ).select().first()
        current.session.resource_id = resource.id

    if resource:
        db.comment.resource_id.default = resource.id
        comments = db(db.comment.resource_id==resource.id).select()
    else:
        comments = {}

    len_queue = len(current.session.resource_id_queue)
    if len_queue>5:
        current.session.resource_id_queue = current.session.resource_id_queue[-5:]
    len_queue = len(current.session.resource_id_queue)

    return dict(resource=resource, comments=comments, len_queue=len_queue)



@auth.requires_login()
def show():
    #resource = db(db.resource.id==request.args(0)).select().first()
    resource = db.resource(request.args(0)) or redirect(URL('index'))
    db.comment.resource_id.default = resource.id

    #form = SQLFORM(db.comment)
    #if form.process().accepted:
    #    response.flash = 'your comment is posted'

    form = crud.create(db.comment,
            message='您的评论已提交！',
            next=URL(args=resource.id))

    comments = db(db.comment.resource_id==resource.id).select()
    return dict(resource=resource, comments=comments, form=form)

def download():
    return response.download(request, db)

def user():
    return dict(form=auth())

@auth.requires_membership('manager')
def manage():
    grid = SQLFORM.smartgrid(db.resource)
    return dict(grid=grid)
